package org.example.shopify;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import lombok.extern.slf4j.Slf4j;
import org.example.xf.ChatUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.*;

/**
 * @Description: ReviewTest
 * @Author wyatt
 * @Data 2024/07/11 18:29
 */
@Slf4j
public class ReviewTest {

    private static final String URL = "https://apps.shopify.com/APPNAMEKEY/reviews?locale=zh-CN&ratings[]=STARKEY";

    private static final String PAGE = "&page=PAGEKEY";

    public static void main(String[] args) {
        int[] stars = new int[]{1,2,3};
        List<String> appNameList = Arrays.asList("automizely-loyalty");
        String app = "referral";
        String excelName = "D:\\Desktop\\shopify\\20240712010_" + app  + ".xlsx";
        exportExcel(appNameList, stars, excelName);
    }

    private static void exportExcel(List<String> appNameList, int[] stars , String excelName) {

        List<ReviewInfo> rows = new ArrayList<>();

        for (String appName : appNameList) {
            for (int star : stars) {
                int page = 1;
                String url = URL;
                String urlNew = url.replace("APPNAMEKEY", appName)
                        .replace("STARKEY", String.valueOf(star));
                while (true){

                    String pageInfo = "";
                    if(page > 1){
                        pageInfo = PAGE.replace("PAGEKEY", String.valueOf(page));
                    }

                    log.info("url : {}", urlNew.concat(pageInfo));
                    try {
                        Document doc = Jsoup.connect(urlNew.concat(pageInfo))
                                .cookies(new HashMap<>()).referrer(url).get();
                        Elements elements = doc.getElementsByClass("lg:tw-grid lg:tw-grid-cols-4 lg:tw-gap-x-gutter--desktop");
                        if(elements.isEmpty()){
                            break;
                        }
                        for(Element element : elements) {

                            String reviewUpdateTime = element.getElementsByClass("tw-text-body-xs tw-text-fg-tertiary").text().replace("编辑时间：", "");
                            String reviewInfo = element.getElementsByClass("tw-mb-xs md:tw-mb-sm").text();

                            String reviewerName = "", reviewerAddress = "", reviewerUseTime = "";
                            try{
                                Elements devElements = element.getElementsByClass("tw-order-2 lg:tw-order-1 lg:tw-row-span-2 tw-mt-md md:tw-mt-0 tw-space-y-1 md:tw-space-y-2 tw-text-fg-tertiary  tw-text-body-xs").get(0).getElementsByTag("div");
                                reviewerName = devElements.get(1).text();
                                reviewerAddress = devElements.get(2).text();
                                reviewerUseTime = devElements.get(3).text().replace("人在使用应用", "");

                            }catch (Exception e){
                                log.info("exportExcel reviewerName {}", urlNew, e);
                            }

                            String answerTime = element.getElementsByClass("tw-text-body-xs tw-text-fg-tertiary tw-mb-sm").text();
                            if(answerTime.contains("已回复")){
                                answerTime = answerTime.substring(answerTime.indexOf("已回复"), answerTime.length()-1);
                            }
                            String answer = element.getElementsByClass("tw-space-y-md").text();

                            log.info(" review :  {}, {}", reviewerName, reviewerUseTime);

                            ReviewInfo review = ReviewInfo.builder()
                                    .appName(appName)
                                    .stars(String.valueOf(star))
                                    .reviewerName(reviewerName)
                                    .reviewerUseTime(reviewerUseTime)
                                    .reviewerAddress(reviewerAddress)
                                    .reviewUpdateTime(reviewUpdateTime)
                                    .reviewInfo(reviewInfo)
                                    .reviewInfoTranslate(ChatUtil.chatTranslate(reviewInfo))
                                    .reviewInfoTag(ChatUtil.chatTranslateSimple(reviewInfo))
                                    .answer(answer)
                                    .answerTranslate(ChatUtil.chatTranslate(answer))
                                    .answerTime(answerTime)
                                    .build();
                            rows.add(review);
                        }

                        Thread.sleep(5000 + new Random().nextInt(5000));

                    }catch (Exception e) {
                        log.info("exportExcel {}", urlNew, e);
                        try {
                            Thread.sleep(2000 + new Random().nextInt(1000));
                        } catch (InterruptedException ex) {
                            throw new RuntimeException(ex);
                        }
                    }
                    page++;
    //                if(page > 2){
    //                    break;
    //                }
                }
            }
        }

        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(excelName);
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
        // 关闭writer，释放内存
        writer.close();
        System.out.println("导出完成" + excelName + " size: "+ rows.size());
    }

}
